﻿using DeHeng_Mes.Constant;
using DeHeng_Mes.Dao;
using DeHeng_Mes.Model.OrderSingleton;
using DeHeng_Mes.Model.Table;
using DeHeng_Mes.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DeHeng_Mes.PlcService
{
    public class EntranceService
    {
        #region 成员实例
        OrderDao orderDao = new OrderDao();
        #endregion

        /// <summary>
        /// 工位入站
        /// </summary>
        /// <param name="station"></param>
        /// <returns></returns>
        public (int, List<int>) StationEntrance(string station, string code)
        {
            // 初始化报警码
            List<int> errorCodes = new List<int>();

            try
            {
                // 获取入站时间
                DateTime now = DateTime.Now;

                switch (station)
                {
                    case SystemConstant.NgStation:

                        // 记录NG工位入站
                        orderDao.NgStationSave(new NgStation()
                        {
                            CreateTime = now,
                            Station = station,
                            TraceId = code,
                            Status = "2"
                        });

                        return (1, errorCodes);
                    default:
                        bool isSave = orderDao.InsertStationStartTime(code, station, now);

                        if (isSave)
                            Tools.ProduceLogText($"[{station}]触发入站存储，入站时间[{now}]，追溯码[{code}]");

                        return (1, errorCodes);
                }
            }
            catch (Exception ex)
            {
                errorCodes.Add(1505);

                Tools.ProduceLogTextError($"[{station}]触发入站失败，原因是[{ex.Message}]");

                return (-1, errorCodes);
            }
        }

        /// <summary>
        /// 入站绑定工单
        /// </summary>
        /// <param name="station"></param>
        public void CodeBandingOrder(string station, string code)
        {
            if (!station.Equals(SystemConstant.OP10))
                return;

            try
            {
                // 根据当前工位获取生产的物料 => 根据物料获取当前物料的关联工单
                OrderSingletonModel orderSingletonModel = OrderSingleton.Instance.Where(x => x.MaterialId.Equals(SystemConstant.AUTO_P6_MATERIALID)).FirstOrDefault();

                if (orderSingletonModel == null)
                    return;

                bool isSave = orderDao.InsertOrderTrace(orderSingletonModel.OrderId, code, orderSingletonModel.LineName);

                if (isSave)
                {
                    Tools.ProduceLogText($"[{orderSingletonModel.OrderId}]触发入站绑定工单，绑定码[{code}]");
                }
            }
            catch (Exception ex)
            {
                Tools.ProduceLogTextError($"[{station}]触发入站工单绑定失败，原因是[{ex.Message}]");
            }
        }
    }
}
